const std = @import("std");
const jetzig = @import("jetzig");
const article_service = @import("../../../service/article_service.zig");
const article_model = @import("../../../model/article.zig");
const const_val = @import("../../../utils/const_value.zig");
const myjwt = @import("../../../utils/myjwt.zig");

/// 写文章页
pub fn index(req: *jetzig.Request) !jetzig.View {
    return req.render(.ok);
}

/// 发布文章
pub fn post(req: *jetzig.Request, data: *jetzig.Data) !jetzig.View {
    const token = req.getHeader("authorization") orelse "";
    // std.debug.print("token: {s}\n", .{token});
    // token为空时，返回401
    if (token.len == 0) {
        var root = try data.object();
        try root.put("code", 401);
        try root.put("msg", "token有误");
        try root.put("data", null);
        return req.fail(.unauthorized);
    }

    // 验证token
    const exp = myjwt.ExpectedPayload{ .iss = const_val.JWT_ISS, .sub = const_val.JWT_SUB };
    const is_ok = myjwt.verifyToken(exp, token) catch false;
    if (!is_ok) {
        var root = try data.object();
        try root.put("code", 401);
        try root.put("msg", "token验证失败");
        try root.put("data", null);
        return req.fail(.unauthorized);
    }

    // 提取body中的请求体数据
    const post_data = try req.expectParams(article_model.ArticleDtoForCreate) orelse {
        return req.fail(.bad_request);
    };

    const result = article_service.addArticle(post_data) catch {
        var root = try data.object();
        try root.put("code", 500);
        try root.put("msg", "服务器内部错误");
        try root.put("data", null);
        return req.fail(.internal_server_error);
    };
    if (!result) {
        var root = try data.object();
        try root.put("code", 500);
        try root.put("msg", "添加文章失败");
        try root.put("data", null);
        return req.fail(.internal_server_error);
    }

    var root = try data.object();
    try root.put("code", 200);
    try root.put("msg", "ok");
    try root.put("data", null);
    return req.render(.created);
}
